package com.huxin.soa.config.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/******************************************
 * @author: 大鹏 (dapeng@51huxin.com)
 * @createDate: 2017/3/24
 * @company: (C) Copyright 阳光互信 2016
 * @since: JDK 1.8
 * @projectName:IntelliJ IDEA
 * @Description:类功能描述
 ******************************************/
public class BaseHttpClient {

    public static String doGet(String url) throws Exception {
        String result = null;

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //设置请求超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(5000).setConnectTimeout(5000)
                    .setSocketTimeout(5000).build();

            HttpGet httpget = new HttpGet(url);
            httpget.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpget);

            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
            }

            response.close();
        } finally {
            httpclient.close();
        }

        return result;
    }
}
